<script setup lang="ts">
import { PropType, ref, unref,computed, onMounted } from 'vue'
import type { TableData } from '@/api/account/types'
import { Dialog } from '@/components/Dialog'
import UpdateRevenue from './UpdateRevenue.vue'
import { ElTable, ElTableColumn } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { getIohistoryApi,saveScoreIcomeApi } from '@/api/account'
import type { DescriptionsSchema } from '@/components/Descriptions'


const { t } = useI18n()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<TableData>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const selectedDay = ref<number | null>(null)
const dateRange = ref<[Date, Date] | undefined>(undefined)
const selectedDayExpenditure = ref<number | undefined>(undefined)
const selectedDayScore = ref<number | undefined>(undefined)

// 初始化日期范围为当前月份
const initDateRange = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth()
  const startDate = new Date(year, month, 1)
  const endDate = new Date(year, month + 1, 0)
  dateRange.value = [startDate, endDate]
}

// 用于兼容的 currentDate（用于对话框等地方）
const currentDate = computed(() => {
  if (dateRange.value && dateRange.value[0]) {
    return dateRange.value[0]
  }
  return new Date()
})


// 存储API获取的交易记录列表
const transactionList = ref<Array<{
  ctime?: string
  otype?: number
  amount?: number | string
  coin?: string
  address?: string
}>>([])

// 存储API获取的统计数据
const statsData = ref({
  depNum: 0,
  deposit: 0,
  witNum: 0,
  withdraw: 0,
  sltDepNum: 0,
  sltDeposit: 0,
  sltWitNum: 0,
  sltWithdraw: 0
})

// 当前选中的日期（存储完整的Date对象）
const selectedDate = ref<Date | null>(null)

// 获取日期范围内的收益数据
const fetchMonthlyProfits = async () => {
  if (!dateRange.value) {
    return
  }
  
  const startDate = dateRange.value[0]
  const endDate = dateRange.value[1]
  
  // 格式化为 YYYY-MM-DD 格式
  const startDateStr = `${startDate.getFullYear()}-${(startDate.getMonth() + 1).toString().padStart(2, '0')}-${startDate.getDate().toString().padStart(2, '0')}`
  const endDateStr = `${endDate.getFullYear()}-${(endDate.getMonth() + 1).toString().padStart(2, '0')}-${endDate.getDate().toString().padStart(2, '0')}`
  
  try {
    const res = await getIohistoryApi({
      id: props.currentRow?.id || 0,
      beginday: startDateStr,
      endday: endDateStr
    })
    
    // 更新统计数据
    if (res && res.data) {
      statsData.value = {
        depNum: res.data.depNum ? +res.data.depNum : 0,
        deposit: res.data.deposit ? +res.data.deposit : 0,
        witNum: res.data.witNum ? +res.data.witNum : 0,
        withdraw: res.data.withdraw ? +res.data.withdraw : 0,
        sltDepNum: res.data.sltDepNum ? +res.data.sltDepNum : 0,
        sltDeposit: res.data.sltDeposit ? +res.data.sltDeposit : 0,
        sltWitNum: res.data.sltWitNum ? +res.data.sltWitNum : 0,
        sltWithdraw: res.data.sltWithdraw ? +res.data.sltWithdraw : 0
      }
    }
    // 处理API返回的交易记录数据
    if (res?.data?.items) {
      transactionList.value = res.data.items.map((item: any) => ({
        ctime: item.ctime || '',
        otype: item.otype !== undefined ? +item.otype : undefined,
        amount: item.amount !== undefined ? item.amount : undefined,
        coin: item.coin || '',
        address: item.address || ''
      }))
    } else {
      transactionList.value = []
    }
  } catch (error) {
    console.error('获取交易记录失败:', error)
    // 如果API调用失败，清空数据
    transactionList.value = []
  }
}
const writeRef = ref<ComponentRef<typeof UpdateRevenue>>()

const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log('======',formData)
  if (formData) {
    saveLoading.value = true
    const res = await saveScoreIcomeApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      // currentPage.value = 1
      fetchMonthlyProfits()
    }
  }
}
// 表格数据
const tableData = computed(() => {
  return transactionList.value.map((item) => {
    const currentDateObj = new Date()
    const today = new Date(currentDateObj.getFullYear(), currentDateObj.getMonth(), currentDateObj.getDate())
    let isDisabled = false
    if (item.ctime) {
      const itemDate = new Date(item.ctime)
      const selectedDateObj = new Date(itemDate.getFullYear(), itemDate.getMonth(), itemDate.getDate())
      isDisabled = selectedDateObj > today
    }
    
    return {
      ...item,
      isDisabled
    }
  })
})

// 格式化交易类型
const getTransactionType = (otype?: number) => {
  if (otype === 0) return '充值'
  if (otype === 1) return '提现'
  return '-'
}

const revenue = (row: any) => {
  // 检查日期是否大于当前日期
  if (row.isDisabled) {
    return
  }
  
  // 如果行数据有ctime，使用ctime作为选中日期
  if (row.ctime) {
    const itemDate = new Date(row.ctime)
    selectedDate.value = itemDate
    selectedDay.value = itemDate.getDate()
  }
  
  // 获取当天的数据（保持原有逻辑兼容）
  selectedDayExpenditure.value = row.otype === 1 ? row.amount : undefined
  
  // 获取当天的score值（如果有）
  selectedDayScore.value = undefined
  
  // 构建完整的年月日日期字符串
  if (row.ctime) {
    const itemDate = new Date(row.ctime)
    const fullDate = `${itemDate.getFullYear()}年${(itemDate.getMonth() + 1).toString().padStart(2, '0')}月${itemDate.getDate().toString().padStart(2, '0')}日`
    dialogTitle.value = t('account.UpdateRevenue') + fullDate
  }
  
  actionType.value = 'updateRevenue'
  dialogVisible.value = true
}

// 移除 watch，避免重复请求，只通过 handleDateChange 触发

// 组件挂载时获取初始数据并选中当天
onMounted(() => {
  initDateRange()
  fetchMonthlyProfits()
  // 默认选中当天
  const today = new Date()
  if (dateRange.value) {
    const startDate = dateRange.value[0]
    const endDate = dateRange.value[1]
    // 如果当天在日期范围内，则选中
    if (today >= startDate && today <= endDate) {
      selectedDate.value = new Date(today.getFullYear(), today.getMonth(), today.getDate())
    }
  }
})
</script>

<template>
  <div class="calendar-container">
    <!-- 统计信息卡片 -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-label">{{ '充值次数' }}</div>
        <div class="stat-value">{{ statsData.depNum }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">{{ '充值金额' }}</div>
        <div class="stat-value">{{ statsData.deposit.toFixed(2) }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">{{ '提现次数' }}</div>
        <div class="stat-value">{{ statsData.witNum }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">{{ '提现金额' }}</div>
        <div class="stat-value">{{ statsData.withdraw.toFixed(2) }}</div>
      </div>
    </div>


    <!-- 表格组件 -->
    <div class="table-wrapper">
      <ElTable
        :data="tableData"
        style="width: 100%"
        :row-class-name="({ row }) => row.isDisabled ? 'disabled-row' : ''"
        @row-click="(row) => !row.isDisabled && revenue(row)"
        max-height="600"
      >
        <ElTableColumn prop="ctime" label="创建时间" align="center" min-width="160">
          <template #default="{ row }">
            <span v-if="row.ctime">{{ row.ctime }}</span>
            <span v-else class="empty-text">-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="otype" label="交易类型" align="center" min-width="100">
          <template #default="{ row }">
            <span>{{ getTransactionType(row.otype) }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="amount" label="金额" align="center" min-width="120">
          <template #default="{ row }">
            <span v-if="row.amount !== undefined && row.amount !== null">{{ row.amount }}</span>
            <span v-else class="empty-text">0</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="coin" label="币种" align="center" min-width="100">
          <template #default="{ row }">
            <span v-if="row.coin">{{ row.coin }}</span>
            <span v-else class="empty-text">0</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="address" label="地址" align="center" min-width="200">
          <template #default="{ row }">
            <span v-if="row.address">{{ row.address }}</span>
            <span v-else class="empty-text">0</span>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
  </div>

  <Dialog v-model="dialogVisible" width="600px" :maxHeight="400">
    <template #title>
      <span>{{ t('account.UpdateRevenue') }}
        <span style="color: #409eff;">
        {{ currentDate.getFullYear() }}-{{ (currentDate.getMonth() + 1).toString().padStart(2, '0') }}-{{ selectedDay?.toString().padStart(2, '0') }}
      </span>
      </span>
      
    </template>
    <UpdateRevenue
      v-if="actionType === 'updateRevenue'"
      ref="writeRef"
      :current-row="currentRow"
      :selected-day="selectedDay || undefined"
      :current-date="currentDate"
      :selected-day-expenditure="selectedDayExpenditure"
      :selected-day-score="selectedDayScore"
    />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
.calendar-container {
  padding: 12px;
  background: #fff;
  font-size: 12px;
}

/* 顶部UID/操手信息 */
.user-brief {
  display: flex;
  align-items: center;
  gap: 120px;
  margin-bottom: 10px;
  margin-top: -20px;
}

.user-brief .item {
  white-space: nowrap;
}

.user-brief .label {
  color: inherit;
  font-weight: 700;
  margin-right: 6px;
}

.user-brief .value {
  color: inherit;
  font-weight: 700;
}

/* 统计信息卡片 */
.stats-row {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.stat-card {
  flex: 1;
  text-align: center;
  padding: 8px 12px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
}

.stat-label {
  font-size: 11px;
  color: #666;
  margin-bottom: 4px;
  white-space: nowrap;
}

.stat-value {
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
  white-space: nowrap;
}

/* 顶部信息栏 */
.header-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 8px;
  padding: 0px;
}

/* 日期选择器容器 */
.date-picker-wrapper {
  display: flex;
  align-items: center;
}

/* 表格组件 */
.table-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
}

:deep(.el-table) {
  font-size: 12px;
  
  .disabled-row {
    cursor: not-allowed;
    background: #f5f5f5;
    
    .el-table__cell {
      color: #333 !important;
      padding: 6px 0;
    }
  }
  
  .disabled-row:hover {
    background: #f5f5f5 !important;
  }
  
  .el-table__row {
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .el-table__row:not(.disabled-row):hover {
    background: #f0f9ff;
  }
  
  .el-table__cell {
    color: #333;
    padding: 6px 0;
  }
  
  .el-table__header-wrapper {
    .el-table__cell {
      padding: 8px 0;
      font-size: 12px;
    }
  }
}

.empty-text {
  color: #333;
  font-size: 12px;
}

/* 按钮样式调整 */
:deep(.el-button.is-circle) {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
